package cs3220;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class PostAssembler {
	private BufferedReader tmpIn;
	private BufferedWriter mifOut;
	private String fileName;
	
	public PostAssembler(String fileName) {
		this.fileName = fileName;
		try {
			tmpIn = new BufferedReader(new FileReader(fileName+".tmp"));
			System.out.println("Opened temporary file: "+fileName+".tmp.");
			mifOut = new BufferedWriter(new FileWriter(fileName+".mif"));
			System.out.println("Created memory file: "+fileName+".mif.");
		} catch (IOException e) {
			System.err.println("error opening files in post processor");
		}
	}
	
	public void run(String width, String depth) {
		String line;
		long currAddress = 0, parsed = -1;
		
		try {
			mifOut.write("WIDTH="+width+";\n");
			mifOut.write("DEPTH="+depth+";\n");
			mifOut.write("ADDRESS_RADIX=HEX;\n");
			mifOut.write("DATA_RADIX=HEX;\n");
			mifOut.write("CONTENT BEGIN\n");
			
			while(tmpIn.ready()) {
				line = tmpIn.readLine();
				//System.out.println("String version of address is:"+line.substring(0,8));
				parsed = Long.parseLong(line.substring(0, 8), 16);
				//System.out.println("Parsed address: "+parsed);
				if(currAddress == 0) {
					//System.out.println("Current was 0.");
					mifOut.write("[00000000.."+hexStrSizer(8,Long.toHexString(parsed-1))+"] : DEADBEEF;\n");
				} else if(parsed > currAddress+2) {
					//System.out.println("Range was from:"+currAddress+" to:"+parsed);
					mifOut.write("["+hexStrSizer(8,Long.toHexString(currAddress+1))+".."+hexStrSizer(8,Long.toHexString(parsed-1))+"] : DEADBEEF;\n");
				} else if(parsed == currAddress+2) {
					//System.out.println("Single gap found at"+(parsed-1)+".");
					mifOut.write(hexStrSizer(8,Long.toHexString(parsed-1))+" : DEADBEEF;\n");
				}
				mifOut.write(line+"\n");
				currAddress = parsed;
				//System.out.println("New current: "+currAddress);
			}

			parsed = Long.parseLong(depth);
			mifOut.write("["+hexStrSizer(8,Long.toHexString(currAddress+1))+".."+hexStrSizer(8,Long.toHexString(parsed-1))+"] : DEADBEEF;\n");
			mifOut.write("END;\n");
			mifOut.flush();
		} catch (IOException e) {
			//Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Processed memory file: "+fileName+".mif.");
	}
	
	public void cleanUp() {
		try {
			mifOut.close();
			tmpIn.close();
		} catch (IOException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String hexStrSizer(int size, String curr) {
		int len = curr.length();
		
		if(len > size) { //concat LSB
			return curr.substring(len-size);
		}
		
		char toPadd = '0';
		
		String toRet = "";
		for(int i = 0; i < size-len; i++ ) {
			toRet+=toPadd;
		}
		toRet += curr;
		return toRet;
	}
	
	
}
